package org.bees.cms.web.action.style;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.bees.cms.core.Domain;
import org.bees.cms.core.Named;
import org.bees.cms.core.style.Template;
import org.bees.cms.service.Service;
import org.bees.cms.service.style.TemplateService;
import org.bees.cms.web.action.EditActionSupport;
import org.bees.cms.web.action.StaticizeAction;
import org.bees.cms.web.util.Pages;
import org.bees.cms.web.util.Staticizer;
import org.bees.cms.web.util.velocity.Configuration;
import org.bees.cms.web.util.velocity.Context;
import org.bees.cms.web.util.velocity.global.Querier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Scope("prototype")
@Controller
public class TemplateEditAction extends EditActionSupport<Template> implements StaticizeAction {
	@Resource
	private TemplateService templateServiceBean;

	@Override
	public Service<Template> service() {
		return templateServiceBean;
	}

	@Override
	public String staticize() throws Exception {
		if (ids != null && ids.length > 0) {
			List<Template> templates = templateServiceBean.find(Arrays.asList(ids));
			for (Template template : templates) {
				Context context = new Context();
				context.put(Pages.SELF, template);
				List<?> domains = null;
				if (!template.getMapper().trim().equals("")) {
					domains = new Querier().query(Configuration.getTable(template.getMapper()), template.getCriterion(), template.getSorting(), template.getRestriction());
					context.put(Pages.DOMAINS, domains);
				}
				switch (template.getScope()) {
				case SINGLE: {
					String path = template.getDirectory() + "/" + template.getPrefix() + "." + template.getSuffix();
					Staticizer.staticize(path, context, template.getContent());
					break;
				}
				case MULTIPLE: {
					for (Object object : domains) {
						Domain domain = (Domain) object;
						context.put(Pages.DOMAIN, domain);
						String name = template.getPrefix();
						if (domain instanceof Named) {
							Named named = (Named) domain;
							name = name + "-" + named.getName() + "." + template.getSuffix();
						} else {
							name = name + "-" + domain.getId() + "." + template.getSuffix();
						}
						String path = template.getDirectory() + "/" + name;
						Staticizer.staticize(path, context, template.getContent());
					}
					break;
				}
				default:
					break;
				}
			}
		}
		request.setAttribute(Pages.MESSAGE, "静态化成功!");
		return MESSAGE;
	}

	@Override
	public Template getDomain() {
		return domain;
	}

	@Override
	public void setDomain(Template domain) {
		this.domain = domain;
	}
}
